<?php
namespace Api\Controller;
use Common\Model\GameModel;
use Common\Model\MerchPayModel;
use Common\Model\RedpackModel;
use Common\Model\UserModel;
use Common\Model\UtilsModel;
use Common\Model\WeixinModel;
use Think\Controller;
class GameController extends Controller {
    const SUCCESS   =0;//成功
    const FAILURE   =1;//失败
    public function index(){
        $this->show('公共支持','utf-8');
    }




    /**
     * 提交星探结果，
     */
    public function submitStarResult(){
        $gid=I('post.gid',0,'intval');//游戏编号
        $oid=I('post.oid',0,'intval');//对家uid
        $uid=session('uid');//自己uid
        $sid=I('post.sid',0,'intval');//选中uid
        $userInfo=UserModel::getUserInstance()->find($uid);


        if($oid == $sid){//正确
            $result=GameModel::BET_RESULT_WIN;
        }else{//错误
            $result=GameModel::BET_RESULT_LOSE;
        }

        $return=array('status'=>0,
            'msg'=>'success',
            'result'=>$result,//对错，1对
            'prize'=>0,//获得奖励
            'return'=>0,//对赌退回
            'next'=>'' //下一组
        );

        if(true){//明星赛
            $update=array();
            if($result==GameModel::BET_RESULT_WIN){
                $userInfo['nowScore']+=1;
                $update['nowScore']=$userInfo['nowScore'];
                $userInfo['point'] += WIN_POINT;
                $update['point'] =$userInfo['point'];
                if($userInfo['historyScore']<$userInfo['nowScore']){
                    $oldTitle=UserModel::getTitle($userInfo['historyScore']);
                    $newTitle=UserModel::getTitle($userInfo['nowScore']);
                    if (strcasecmp($oldTitle,$newTitle)!=0){
                        $return['title']=$newTitle;
                    }

                    $userInfo['historyScore']=$userInfo['nowScore'];
                    $userInfo['historyTime']=time();

                    $update['historyScore']=$userInfo['historyScore'];
                    $update['historyTime']=$userInfo['historyTime'];
                }
                $return['point']        = $userInfo['point'];
                $return['nowScore']     = $userInfo['nowScore'];
                $return['historyScore'] = $userInfo['historyScore'];
                $return['next'] = $this->getNextTeam( $userInfo['nowScore']);
            }else{
                $userInfo['nowScore']=0;
                $update['nowScore']=$userInfo['nowScore'];

                $this->initGame();//重置明星序列
            }

            UserModel::getUserInstance()->where("uid={$uid}")->save($update);
        }


        $this->ajaxReturn($return);
    }

    /**
     * 提交素人游戏结果，
     */
    public function submitSurenResult(){
        $gid=I('post.gid',0,'intval');//游戏编号
        $jid=I('post.jid',0,'intval');//游戏参与编号
        $selected=I('post.pic');//选中图片,或者位置位置





        $gameInfo=GameModel::getGameInstance()->where("gid={$gid}")->field('album,isBet,uid,type,extra')->find();
        if (!$selected || !$gameInfo){
            $result=GameModel::BET_RESULT_LOSE;
        }
        else{
            if (strcasecmp($gameInfo['type'],'single')==0){//单人照
                if(strpos($gameInfo['album'],$selected)===false){
                    $result=GameModel::BET_RESULT_LOSE;
                }else{
                    $result=GameModel::BET_RESULT_WIN;
                }
            }else{//合照
                list($x,$y,$scale)=explode(',',$gameInfo['extra']);
                list($x2,$y2,$scale2)=explode(',',$selected);
                $diff_x=abs( $x*$scale2 - $x2*$scale);
                $diff_y=abs( $y*$scale2 - $y2*$scale);
                if ($diff_x<20 && $diff_y<20){
                    $result=GameModel::BET_RESULT_WIN;
                }else{
                    $result=GameModel::BET_RESULT_LOSE;
                }
            }
        }

        $return=array('status'=>0,'result'=>$result,'return'=>0,'prize'=>0);

        $uid=session('uid');//自己uid
        //join记录更新
        $joinInfo=GameModel::getJoinInstance()->where("jid={$jid} and uid={$uid}")->find();
        if (!$joinInfo){
            $return=array('status'=>1,'msg'=>'您尚未参与游戏，不能接受您提交的结果');
            $this->ajaxReturn($return);
        }
        if ($joinInfo['isRight']!=GameModel::BET_RESULT_UNKNOW){
            $return=array('status'=>1,'msg'=>'您已经参与过本游戏');
            $this->ajaxReturn($return);
        }

        if($result == GameModel::BET_RESULT_WIN){//成功
            if ($gameInfo['isBet']){//游戏是对赌的
                if ($joinInfo['isBet']){//参与对赌
                    GameModel::getPrizeInstance()->startTrans();
                    $prizeRecord=GameModel::getPrizeRecordByGid($gid);
                    if($prizeRecord){
                        UserModel::addMoney($prizeRecord['money'], $uid, GameModel::OPT_BET_WIN, $gameInfo['uid']);
                        $return['prize']=$prizeRecord['money']/100;//奖励
                    }
                    $this->refundWager($joinInfo['jid']);
                    $return['return']=$joinInfo['total_fee']/100;//退回
                }
            }
            else{//游戏不是对赌的
                //判断奖池，随机给奖励
                $prizeRecord=GameModel::getPrizeRecordByGid($gid);
                if ($prizeRecord) {//有奖
                    UserModel::addMoney($prizeRecord['money'], $uid, GameModel::OPT_PRIZE, $gameInfo['uid']);
                    $return['prize']=$prizeRecord['money']/100;//奖励
                }
            }
            if($prizeRecord){//奖励记录更新
                GameModel::setPrizeRecordStatus($prizeRecord['id'],GameModel::PRIZE_RECORD_STATUS_SEND);
            }
        }else{//失败
            if($joinInfo['isBet'] && $gameInfo['isBet']){//保证金转给发起人
                $gotMoney=ceil(BET_FEE*(100-FEE_SCALE)/100);
                UserModel::addMoney($gotMoney,$gameInfo['uid'],GameModel::OPT_BET_LOSE,$uid);
            }
        }

        GameModel::getJoinInstance()->where("jid={$jid} and uid={$uid}")->save(array('isRight'=>$result,'money'=>$return['prize']*100));
        GameModel::getPrizeInstance()->commit();
        $this->ajaxReturn($return);
    }


    /**
     * 游戏余额退款
     */
    public function refundGame(){
        $gid=I('get.gid',0,'intval');
        $uid=session('uid');
        $ginfo=GameModel::getGameInstance()->where("gid={$gid} && uid={$uid}")->find();
        if($ginfo['hasPay']!=1 ){
            $this->ajaxReturn(array('status'=>1,'msg'=>"本游戏未曾支付，不可退款了"));
        }
        if($ginfo['refundMoney']>=$ginfo['total_fee']){
            $this->ajaxReturn(array('status'=>1,'msg'=>"本游戏已经退过款了，不可重复操作"));
        }

        $sendOut=GameModel::getJoinInstance()->where("gid={$gid}")->sum('money');
        $refundMoney=$ginfo['totalPrize']-$sendOut;
        $refundInfo=array(
            'outRefundNo'   => $ginfo['out_trade_no'],
            'outTradeNo'    => $ginfo['out_trade_no'],
            'total'         => $ginfo['total_fee'],
            'refund'        => $refundMoney
        );
        $result=WeixinModel::refund($refundInfo);
        if($result['status']==0){
            GameModel::getGameInstance()->where("gid={$gid} && uid={$uid}")->save(array('refundMoney'=>$refundMoney,'hasPay'=>GameModel::REFUND));
            RedpackModel::getRecordInstance()->where("setId={$gid} and status=".GameModel::PRIZE_RECORD_STATUS_UNSEND)->setField('status',GameModel::PRIZE_RECORD_STATUS_REFUND);
        }
        $this->ajaxReturn($result);
    }

    /**
     * 保证金退款
     */
    private function refundWager($jid){
        $uid=session('uid');
        $jinfo=GameModel::getJoinInstance()->where("jid={$jid} && uid={$uid}")->find();
        if($jinfo['hasPay']!=1 || $jinfo['refundMoney']>=$jinfo['total_fee']){
            $this->ajaxReturn(array('status'=>1,'msg'=>"当前状态不可以退款"));
        }
        $refundInfo=array(
            'outRefundNo'   => $jinfo['out_trade_no'],
            'outTradeNo'    => $jinfo['out_trade_no'],
            'total'         => $jinfo['total_fee'],
            'refund'        => $jinfo['total_fee']
        );
        $result=WeixinModel::refund($refundInfo);
        if($result['status']==0){
            $result['refund']=$result['data']['total_fee']/100;
            unset($result['data']);
            GameModel::getJoinInstance()->where("jid={$jid} && uid={$uid}")->setField('refundMoney',$jinfo['total_fee']);
        }
        return $result;
    }

    /**
     * 初始化明星列表
     */
    private function initGame(){
        $star=UserModel::getStarInstance()->group('sex,race')->getField('GROUP_CONCAT(uid)',true);
        $allstr=implode(',',$star);
        $array=explode(',',$allstr);
        shuffle($array);
        session('starId',implode(',',$array));
        foreach ($star as $k=>$v){
            $star[$k]=explode(',',$v);
        }
        session('starCfg',json_encode($star));
    }

    /**
     * 取下一组明星
     * @param $nowScore， 当前答对的明星数量
     * @return bool|mixed
     */
    public function getNextTeam($nowScore=0){
        $idStr=session('starId');
        $idArray=explode(',',$idStr);
        if(!array_key_exists($nowScore,$idArray)){
            $nowScore = $nowScore % count($idArray);
        }

        $nextStarId=$idArray[$nowScore];//下一场要答的主咖编号
        $uidArr=array();
        $uidArr[]=$nextStarId;

        $starName=UserModel::getStarInstance()->where("uid={$nextStarId}")->getField('nickname');


        $starCfg=session('starCfg');
        $cfg=json_decode($starCfg,true);
        $back=null;
        foreach ($cfg as $ones){
            if(array_search($nextStarId,$ones)!==false){
                $others=array_rand($ones,6);
                $back=$ones;
                break;
            }
        }
        foreach ($others as $pos){
            if($back[$pos] == $nextStarId){
                continue;
            }
            $uidArr[]=$back[$pos];
        }
        if(count($uidArr)>6){
            unset($uidArr[6]);
        }
        return array('status'=>0,'starName'=>$starName,'list'=>$this->getStarPhotos($uidArr));
    }


    /**
     * 明星游戏
     */
    public function startStarGame(){
        $uid=session('uid');
        $uinfo=UserModel::getUserInstance()->where("uid={$uid}")->find();
        if ($uinfo['point'] < PLAY_POINT){
            $this->ajaxReturn(array(
                'status'=>1,
                'msg'=>'积分不足'
            ));
        }else{
            UserModel::getUserInstance()->where("uid={$uid}")->setDec('point',PLAY_POINT);
        }

        $this->initGame();
        $this->ajaxReturn(array(
                'point'     => $uinfo['point']-PLAY_POINT,
                'next'      => $this->getNextTeam(0)
            )
        );
    }



    private function getStarPhotos(&$idarray){
        $idstr=implode(',',$idarray);
        $list= UserModel::getStarInstance()->where("uid in ($idstr)")->field('uid,headPic,album')->select();
        foreach($list as $k=>$v){

            $imgs=explode(',',$v['album']);
            $idx=array_rand($imgs,1);
            $list[$k]['album']=$imgs[$idx];

            if( $idarray[0] != $v['uid'] ){
                unset($list[$k]['headPic']);
            }
        }
        shuffle($list);
        return $list;
    }

    /**
     * 素人
     */
    public function startSurenGame(){
        $gid=I('post.gid',0,'intval');
        $detail=GameModel::getGameInstance()->where('gid='.$gid)->field('album,target,relay,audit,hasPay,isBet,uid,type')->find();
        if ($detail['audit']!=PHOTO_AUDIT_PASS || $detail['hasPay']!=1){
            $this->ajaxReturn(array('status'=>1,'msg'=>'游戏暂时未开通'));
        }
        $uid=session('uid');
        $playLog=GameModel::getJoinInstance()->where("gid={$gid} and uid={$uid}")->find();//已存在的游戏记录
        if($playLog && $playLog['isRight']!=GameModel::BET_RESULT_UNKNOW) {
            $this->ajaxReturn(array('status' => 1, 'msg' => '您已参加过本游戏'));
        }
        if($detail['isBet']==1){
            if(!$playLog || $playLog['hasPay']!=1) {
                $this->ajaxReturn(array('status' => 2, 'msg' => '本游戏需要您支付保证金'));
            }else{
                $jid=$playLog['jid'];
            }
        }else{
            if(!$playLog){
                $jid=GameModel::getJoinInstance()->add(array('gid'=>$gid,'uid'=>$uid,'addTime'=>time(),'isRight'=>GameModel::BET_RESULT_UNKNOW));
            }else{
                $jid=$playLog['jid'];
            }
        }

        $pic=UserModel::getUserInstance()->where("uid={$detail['uid']}")->getField('headPic');

        if ($detail['type']=='single') {

            $mainArr = explode(',', $detail['album']);
            shuffle($mainArr);
            $photos = array();
            $photos[] = $mainArr[0];

            $stars = UserModel::getStarInstance()->where("length(album)>10")->limit(5)->getField('album', true);
            foreach ($stars as $album) {
                $mainArr = explode(',', $album);
                shuffle($mainArr);
                $photos[] = $mainArr[0];
            }
            shuffle($photos);
        }else{//group
            $photos=$detail['album'];
        }

        $this->ajaxReturn( array('status'=>0,'list'=>$photos,'type'=>$detail['type'],'jid'=>$jid,'pic'=>$pic,'target'=>$detail['target'],'relay'=>$detail['relay']));
    }


    /**
     *
     */
    public function getIncomeLog(){
        $uid=session('uid');
        $data=M('l_log',null,DB_MAIN_CFG)->where("uid={$uid}")->order('lid desc')->field('msg,from_unixtime(addTime,"%m-%d %H:%i") as date')->select();
        $this->ajaxReturn(array('list'=>$data));
    }
    

    /**
     * 用户进入
     */
    public function userLogin(){
        $openId     = I('post.openId');
        $headPic    = I('post.headPic');
        $sex        = I('post.gender');
        $nickname   = I('post.nickname');
        $this->ajaxReturn(UserModel::login($openId,$nickname,$headPic,$sex));
    }

    /**
     * 更新图集
     */
    public function editGame(){
        $uid=session('uid');
        if(!$uid){
            $this->ajaxReturn(array('status'=>1,'msg'=>'请授权登陆游戏'));
        }

        $albumStr   = I('post.album');
        $target     = I('post.target');
        $formId     = I('post.formId');
        $type       = I('get.t','single');
        $extra      = I('post.extra');


        

        $result=UserModel::editGame($uid,$albumStr,$target,$type,$extra);

        if($result['status']==1){
            $this->sendTemplateMsg_audit($result['gid'],ADMIN_OPENID);
        }
        $this->ajaxReturn($result);

    }

    private function sendTemplateMsg_lack($openID,$needMoney){
        $templateId=MONEY_LACK_TEMPLATE;
        $templateMsg=array(
            'touser'=>$openID,
            'template_id'=>$templateId,
            'url'=>'',
            "topcolor"=>"#FF0000",
            'data'=>array(
                "first"=>array(
                    "value"=>"你好，有用户提现失败",
                    "color"=>"#173177"
                ),
                "keyword1"=>array(
                    "value"=>($needMoney/100).'元',
                    "color"=>"#173177"
                ),
                "keyword2"=>array(
                    "value"=>'运营账户余额',
                    "color"=>"#173177"
                ),
                "remark"=>array(
                    "value"=>"请尽快进入商户后台给运营账户充值",
                    "color"=>"#173177"
                ),

            )
        );
        $content=json_encode($templateMsg);

        WeixinModel::sendTemplateMsg($content);
    }

    /**
     * 发送咨询模板消息
     * @param $gid 游戏编号
     * @param null $openID
     */
    private  function sendTemplateMsg_audit($gid,$openID=null){
        $templateId=APPLY_TEMPLATE;

        $templateMsg=array(
            'touser'=>$openID,
            'template_id'=>$templateId,
            'url'=>'https://findme.bibei365.com/api.php?c=Game&a=audit&gid='.$gid,
            "topcolor"=>"#FF0000",
            'data'=>array(
                "first"=>array(
                    "value"=>"你好，有用户新增活动申请，请尽快审核",
                    "color"=>"#173177"
                ),
                "keyword1"=>array(
                    "value"=>$gid,
                    "color"=>"#173177"
                ),
                "keyword2"=>array(
                    "value"=>'用户所传图片存在色情嫌疑',
                    "color"=>"#173177"
                ),
                "remark"=>array(
                    "value"=>"点击本信息即可进入审核界面，进行操作",
                    "color"=>"#173177"
                ),

            )
        );
        $content=json_encode($templateMsg);

        WeixinModel::sendTemplateMsg($content);
    }

    /**
     * 支付
     */
    public function buildOrder(){
        $gid=I('post.gid',0,'intval');
        $prizeMoneyYuan=I('post.prizeMoney',0,'floatval');
        
        $num=I('post.num',1,'intval');
        $minYuan=I('post.min',1,'floatval');

        $isBet=I('post.isBet',1,'intval');
        $relay=I('post.relay',1,'intval');
        if($prizeMoneyYuan<1){
            $this->ajaxReturn(array('status'=>1,'msg'=>'红包金额至少为1元'));
        }
        if($num<1){
            $this->ajaxReturn(array('status'=>1,'msg'=>'红包个数至少为1个'));
        }
        if($minYuan<1){
            $this->ajaxReturn(array('status'=>1,'msg'=>'最小红包至少为1元'));
        }

        $prizeMoneyFen  = $prizeMoneyYuan*100;
        $minFen         = $minYuan*100;
        
        if (!RedpackModel::checkAssign($prizeMoneyFen,$num,$minFen)){
            $this->ajaxReturn(array('status'=>1,'msg'=>'总红包金额不够分配'));
        }

        $fee=ceil($prizeMoneyFen * FEE_SCALE /100);
        $uid=session('uid')+0;
        $result=GameModel::getGameInstance()->where('gid='.$gid.' and uid='.$uid)->save(array(
            'totalPrize'=>$prizeMoneyFen,
            'packNum'=>$num,
            'packMin'=>$minFen,
            'isBet'=>$isBet,
            'relay'=>$relay,
            'fee'=>$fee
        ));
        if($result===false){
            $this->ajaxReturn(array('status'=>1,'msg'=>'服务器出现错误，请过段时间再试'));
        }else{
            $this->ajaxReturn(array('status'=>0,'gid'=>$gid,'totalMoney'=>($fee+$prizeMoneyFen)/100));
        }
    }


    /**
     * 支付赌注订单
     */
    public function wagerOrder(){
        $gid=I('post.gid',0,'intval');//游戏编号
        $uid=session('uid')+0;
        $wid=GameModel::getJoinInstance()->where("gid={$gid} and uid={$uid} and hasPay=0")->getField('jid');
        if(!$wid) {
            $wid = GameModel::getJoinInstance()->add(array(
                'gid'       => $gid,
                'uid'       => $uid,
                'addTime'   => time(),
                'hasPay'    => 0,
                'isBet'     => 1
            ));
        }
        if($wid===false){
            $this->ajaxReturn(array('status'=>1,'msg'=>'服务器出现错误，请过段时间再试'));
        }else{
            $this->ajaxReturn(array('status'=>0,'wid'=>$wid,'fee'=>BET_FEE/100));//费用单位：元
        }
    }




    /**
     * 星探排行
     */
    public function starRank(){
        //pre_dump($_REQUEST);
        $uid=session('uid');
        $list=UserModel::getUserInstance()->order('historyScore desc,historyTime asc')->field('nickname as name,headPic as icon,historyScore as score')->limit(9)->select();
        $mine=UserModel::getUserInstance()->where('uid='.$uid)->find();
        $rank=UserModel::getUserInstance()->where("uid <> {$uid} and historyScore >{$mine['historyScore']}")->count()+1;

        foreach ($list as $k=>$v){
            $list[$k]['title']= UserModel::getTitle($v['score']);
        }

        $this->ajaxReturn(
            array('list'=>$list,'rank'=>$rank,'title'=>UserModel::getTitle($mine['historyScore']))
        );
    }


    public function getWXopenid(){
        $jscode=I('get.js_code');
        //https://api.weixin.qq.com/sns/jscode2session?appid=wx0bc6c5ceddbae730&secret=e774e7f275cca946bcd85e217cd2ebd8&grant_type=authorization_code&js_code=081w1PiU13K1pV0UuWlU1EQOiU1w1PiG
        $data=array(
            'appid'=>XIAO_APPID,
            'secret'=>XIAO_SECRET,
            'grant_type'=>'authorization_code',
            'js_code'=>$jscode
        );
        $return=UtilsModel::curl_request('https://api.weixin.qq.com/sns/jscode2session?','get',$data);
        if($return['status']==0){
            $return['data']=json_decode($return['data'],1);
            $return['data']['sessionId']=md5($return['data']['openid']);
            session('session_key', $return['data']['session_key']);
        }
        $this->ajaxReturn($return);
    }
    public function descriptShare(){
        include_once WEB_ROOT."/Lib/PHP/wxBizDataCrypt.php";
        $pc = new \WXBizDataCrypt(XIAO_APPID, session('session_key'));
        $dataStr='';
        $encryptedData  =I('post.data');
        $iv             =I('post.iv');
        $errCode = $pc->decryptData($encryptedData, $iv, $dataStr );

        if ($errCode == 0) {
            $uid=session('uid');
            $date=date('Y-m-d');
            $data=json_decode($dataStr);
            if(UserModel::getShareInstance()->where("openGid='{$data->openGId}' and uid={$uid} and addDate='{$date}'")->find()){
                $this->ajaxReturn(array('status'=>0,'point'=>0));
            }else{
                UserModel::getShareInstance()->add(array('openGid'=>$data->openGId ,'uid'=>$uid,'addDate'=>$date));
                UserModel::getUserInstance()->where("uid={$uid}")->setInc('point',SHARE_GOT_POINT);
                $this->ajaxReturn(array('status'=>0,'point'=>SHARE_GOT_POINT));
            }
        } else {
            $this->ajaxReturn(array('status'=>1,'msg'=>'分享失败'));
        }
    }


    public function cash(){
        $uid=session('uid');
        $uinfo=UserModel::getUserInstance()->where("uid={$uid}")->field('openId,depositMoney,cashMoney')->find();
        if($uinfo['depositMoney']<100){
            $this->ajaxReturn(array('status'=>1,'msg'=>'提现金额必须大于1元'));
        }

        $now=time();
        $oid=$uid.$now;
        $ret=MerchPayModel::pay($uinfo['openId'],time(),$uinfo['depositMoney'],'找我唷游戏提现');
        if ($ret['return_code'] == 'SUCCESS' && $ret['return_code'] == 'SUCCESS'){
            UserModel::getCashInstance()->startTrans();
            UserModel::getCashInstance()->add( array('no'=>$oid,'uid'=>$uid,'money'=>$uinfo['depositMoney'],'addTime'=>$now) );
            UserModel::getUserInstance()->where("uid={$uid}")->save( array('depositMoney'=>0,'cashMoney'=>$uinfo['cashMoney']+$uinfo['depositMoney']) );
            UserModel::getCashInstance()->commit();
            $this->ajaxReturn(array('status'=>0,'msg'=>'提现成功，请到微信钱包，零钱明细中查看'));
        }else{
            $this->sendTemplateMsg_lack(ADMIN_OPENID,$uinfo['depositMoney']);
            $this->ajaxReturn(array('status'=>1,'msg'=>'提现失败，我们已通知管理员，请您过段时间再试'));
        }

    }



    //模板消息通知审核
    public function audit(){
        $gid=I('get.gid',0,'intval');
        $game=GameModel::getGameInstance()->where("gid={$gid}")->find();
        if(!$game){
            die("指定游戏不存在");
        }
        if ($game['audit'] == PHOTO_AUDIT_UNPASS || $game['audit'] == PHOTO_AUDIT_PASS){
            $s=UserModel::getAuditStatus();
            die("游戏已经执行过审核：".$s[$game['audit']]);
        }


        if (IS_POST){
            $audit=I('post.audit',1,'intval');
            if($audit==1){
                $status=PHOTO_AUDIT_PASS;
            }else{
                $status=PHOTO_AUDIT_UNPASS;
            }

            $result = GameModel::getGameInstance()->where('gid=' . $gid)->setField('audit',$status );

            $pics=str_replace(',',"','",$game['album']);
            $checkStatus =PHOTO_AUDIT_REVIEW.','.PHOTO_AUDIT_UNCHECK;
            M('photo_lib',null,DB_MAIN_CFG)->where("audit in ({$checkStatus})  and path in ('{$pics}')")->setField('audit',$status);
            die('审核完毕');
        }

        


        $smarty=getSmarty();
        $smarty->assign('gid',$gid);
        $smarty->assign('album',$game['album']);
        $smarty->display('gameAudit.html');


    }


    public function getMyGame(){
        $uid=session('uid');
        $user=UserModel::getUserInstance()->where("uid={$uid}")->find();

        $list=GameModel::getGameInstance()->where("uid={$uid}")->field('gid as id,target as title,FROM_UNIXTIME(addTime,\'%m-%d %H:%i\') as date')->order('gid desc')->select();
        $this->ajaxReturn(
            array('uinfo'=>$user,'list'=>$list)
        );
    }


    /**
     * 获取自己游戏基本信息
     */
    public function getGameDetail(){
        $gid=I('get.gid',0,'intval');
        $game=GameModel::getGameInstance()->where("gid={$gid}")->find();
        if(!$game){
            $this->ajaxReturn(array('status'=>1,'msg'=>'指定的游戏不存在'));
        }
        $pics=explode(',',$game['album']);
        
        $auditKv=UserModel::getAuditStatus();

        switch($game['hasPay']){
            case GameModel::UNPAY:
                $payStr='未支付';
                break;
            case GameModel::HASPAY:
                $payStr='已支付';
                break;
            case GameModel::REFUND:
                $payStr='已退款';
                break;
        }
        $detail = array(
            'pic'=>$pics[0],
            'target'    => $game['target'],
            'addTime'   => date('m-d H:i:s', $game['addTime']),
            'audit'     => $game['audit'],
            'auditStr'     => $auditKv[$game['audit']],
            'hasPay'    => $game['hasPay'],
            'payStr'    => $payStr,
            'out'       =>0,
            'type'      =>$game['type'],

        );
        if ($game['audit']==PHOTO_AUDIT_PASS) {
            $detail['totalPrize']   = $game['totalPrize']/100;
            $detail['packNum']      = $game['packNum'];
        }else{
            $detail['totalPrize']   = '未设置';
            $detail['packNum']      = '未设置';
        }
        $list=GameModel::getJoinInstance()->where('gid='.$gid)->select();
        if(count($list)>0) {
            $uidstr = '0';
            foreach ($list as $one) {
                $detail['out'] += $one['money'];
                $uidstr .= ',' . $one['uid'];
            }
            $detail['out'] = $detail['out'] /100;
            $userKv=UserModel::getUserInstance()->where("uid in ({$uidstr})")->getField('uid,nickname,headPic');
            foreach ($list as $k => $one) {
                $list[$k]['nickname']   = $userKv[$one['uid']]['nickname'];
                $list[$k]['icon']       = $userKv[$one['uid']]['headPic'];
                $list[$k]['addTime']    = date('m-d H:i',$one['addTime']);
                $list[$k]['money']      = $one['money']/100;
            }
        }



        $return=array('status'=>0,'detail'=>$detail,'list'=>$list);

        $this->ajaxReturn($return);
    }

    /**
     * 获取别人的游戏基本信息
     */
    public function getOtherGameDetail(){
        $gid=I('post.gid',0,'intval');
        $game=GameModel::getGameInstance()->where("gid={$gid}")->field('uid,target,addTime,audit,hasPay,isBet,relay,type')->find();
        if(!$game){
            $this->ajaxReturn(array('status'=>1,'msg'=>'指定的游戏不存在'));
        }

        $uinfo=UserModel::getUserInstance()->where("uid={$game['uid']}")->field('nickname,headPic')->find();

        $detail = array(
            'nickname'  => $uinfo['nickname'],
            'headPic'  => $uinfo['headPic'],
            'target'    => $game['target'],
            'addTime'   => date('m-d H:i:s', $game['addTime']),
            'audit'     => $game['audit'],
            'hasPay'    => $game['hasPay'],
            'isBet'     => $game['isBet'],
            'relay'     => $game['relay'],
            'hasJoin'   => 0,
            'type'      => $game['type'],
        );

        //是否已参加过该游戏
        $uid=session('uid');
        if(GameModel::getJoinInstance()->where("gid={$gid} and uid={$uid}")->find()){
            $detail['hasJoin']=1;
        }

        $return=array('status'=>0,'detail'=>$detail);

        $this->ajaxReturn($return);
    }



    public function getQRCode(){
        $gid=I('get.gid',0,'intval');
        $qrcode=GameModel::getGameInstance()->where("gid={$gid}")->getField('qrcode');
        if($qrcode && strlen($qrcode)>5){
            $this->ajaxReturn(array("status"=>0,'url'=>$qrcode));
        }else {
            $ret = WeixinModel::getwxacode($gid);
            if ($ret['status']==0){
                GameModel::getGameInstance()->where("gid={$gid}")->setField('qrcode',$ret['url']);
            }
            $this->ajaxReturn($ret);
        }
    }
}